package com.vshop.controller.other;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.vshop.entity.comentity.PartnerAccessRequestRecord;
import com.vshop.entity.interfacerequest.ExceptionRequest;
import com.vshop.entity.interfacerequest.channelaccess.request.RequestAccess;
import com.vshop.entity.interfacerequest.channelaccess.request.RequestAccessData;
import com.vshop.entity.interfacerequest.channelaccess.request.RequestAccessTradeData;
import com.vshop.entity.interfacerequest.channelaccess.response.ResponseAccess;
import com.vshop.entity.interfacerequest.channelaccess.response.ResponseAccessData;
import com.vshop.entity.interfacerequest.channelaccess.response.ResponseAccessTradeData;
import com.vshop.service.PartnerAccessRequestRecordService;
import com.vshop.service.SequenceService;
import com.vshop.utils.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 合作方对接提供的接口：大阳在用！大阳在用！大阳在用！
 *
 * @author lm
 */
@RestController
@Api(description = "H5接入方式入口")
@Slf4j
public class ChannelAccessController {
    public static final String BASE_H5URL = "https://wx.linksfield.net";
    @Autowired
    private SequenceService sequenceService;
    @Autowired
    PartnerAccessRequestRecordService accessService;

    /***
     * 合作伙伴统一的请求接口入口
     * @param
     * @return
     */
    @CrossOrigin
    @ApiOperation(value = "H5方案渠道接入口", response = ResponseAccess.class)
    @PostMapping(value = "/access", produces = "application/json;charset=utf-8")
    public String access(@ApiParam @RequestBody RequestAccess requestAccess) {
        // 1，生成流水号
        String ConnSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());
        ExceptionRequest utils = new ExceptionRequest();

        String jsonString;
        String requestStr = JSON.toJSONString(requestAccess);
        if (requestStr == null) {
            log.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
            return jsonString;
        } else {
            log.info("【H5方案渠道接入口】请求：" + requestStr);
            requestAccess = JSONArray.parseObject(requestStr, RequestAccess.class);
            String requestSign = requestAccess.getSign();
            if (requestAccess.getSign() == null) {
                log.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
                return jsonString;
            } else {
                //获取到要用的参数
                RequestAccessData requestData = requestAccess.getData();
                if (requestAccess.getData() == null) {
                    log.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
                    return jsonString;
                } else {

                    String connSeqNo = requestData.getConnSeqNo();
                    String partnerCode = requestData.getPartnerCode();
                    String token = requestData.getToken();
                    String tradeTime = requestData.getTradeTime();
                    String tradeType = requestData.getTradeType();

                    RequestAccessTradeData tradeData = requestData.getTradeData();
                    if (StringUtils.isBlank(token) || StringUtils.isBlank(partnerCode) || tradeData == null) {
                        log.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {

                        String deviceId = requestData.getTradeData().getDeviceId();
                        String deviceType = requestData.getTradeData().getDeviceType();
                        String notyfy_URL = requestData.getTradeData().getNotyfy_URL();
                        String requestOrderId = requestData.getTradeData().getRequestOrderId();

                        if (StringUtils.isBlank(deviceId) || StringUtils.isBlank(deviceType) || StringUtils.isBlank(notyfy_URL) || StringUtils.isBlank(requestOrderId)) {
                            //参数不全,回复报文
                            log.info("请求报文不合法:tradeData的值为null或者为空");
                            jsonString = utils.dataWeiKong(connSeqNo, curtime);
                            return jsonString;
                        } else {
                            //参数是齐全的，验证签名：
                            String str = JSON.toJSONString(requestData);
                            // 将Str拿去计算签名
                            String sign = utils.calculateSignature(str);
                            log.info("计算的签名是：" + sign);
                            if (!requestSign.equalsIgnoreCase(sign)) {
                                jsonString = utils.signatureFailure(ConnSeqNo, tradeTime, tradeType, "0001", "签名有误，请确认签名！");
                                return jsonString;
                            } else {
                                //签名通过,将合作伙伴访问的记录保存下来
                                //还是应该验证一下相同的请求的话就不要入库了
                                int count = accessService.findAccessByCode(token, partnerCode, deviceId, deviceType, requestOrderId);

                                if (count <= 0) {
                                    //没有记录就入库，有了就不用入库了
                                    PartnerAccessRequestRecord access = new PartnerAccessRequestRecord();
                                    access.setConnSeqNo(connSeqNo);
                                    access.setToken(token);
                                    access.setPartnerCode(partnerCode);
                                    access.setDeviceCode(deviceId);
                                    access.setDeviceType(deviceType);
                                    access.setNotyfy_URL(notyfy_URL);
                                    access.setRequestOrderId(requestOrderId);
                                    access.setTradeTime(tradeTime);
                                    access.setSign(requestSign);
                                    accessService.putInPartnerAccessInfo(access);
                                }
                                ResponseAccessTradeData responseTradeData = new ResponseAccessTradeData();
                                responseTradeData.setDeviceId(deviceId);
                                responseTradeData.setDeviceType(deviceType);
                                responseTradeData.setH5url(BASE_H5URL);
                                responseTradeData.setRequestOrderId(requestOrderId);

                                ResponseAccessData data = new ResponseAccessData();
                                data.setConnSeqNo(connSeqNo);
                                data.setToken(token);
                                data.setPartnerCode(partnerCode);
                                data.setTradeTime(curtime);
                                data.setTradeType(tradeType);
                                data.setTradeRstCode(1000);
                                data.setTradeRstMessage("success");
                                data.setTradeData(responseTradeData);

                                ResponseAccess responseChannelAccess = new ResponseAccess();
                                responseChannelAccess.setData(data);
                                responseChannelAccess.setSign(MD5.calcMD5(JSON.toJSONString(data)));

                                jsonString = JSON.toJSONString(responseChannelAccess);
                                log.info("【H5方案渠道接入口】响应" + jsonString);
                                return jsonString;
                            }
                        }
                    }
                }
            }
        }
    }
}
